package map.android.baidu.carpool.page.home;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;
import com.baidu.mapframework.api2.ComAPIManager;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.baidu.platform.comapi.map.MapUtils;
import com.baidu.platform.comapi.map.config.Preferences;
import map.android.baidu.carpool.CarpoolEntity;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.data.impl.MainConfigData;
import map.android.baidu.carpool.data.impl.MainInfoData;
import map.android.baidu.carpool.model.CarpoolPosition;
import map.android.baidu.carpool.preferences.CarpoolSharedPreferences;
import map.android.baidu.carpool.response.MainConfigResponse;
import map.android.baidu.carpool.response.MainInfoResponse;
import map.android.baidu.carpool.setting.UserInfoSetting;
import map.android.baidu.carpool.utils.SafeUtils;

import java.util.ArrayList;

/**
 * Created by zhangtongyu on 15/3/30.
 * 嵌入基线的View
 */
public class EntranceInRoute{

    private static String TAG = "";

    private LinearLayout mView;
    private ImageView mIconIm;
    private TextView mTitleTv;
    private TextView mPriceTv;
    private TextView mDescTv;

    /**只取本地存储的response 本次网络请求将缓存*/
    private MainConfigResponse mainConfigResponse;
    private IDataStatusChangedListener<MainConfigResponse> mMainConfigResponseListener = new IDataStatusChangedListener<MainConfigResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData<MainConfigResponse> data, MainConfigResponse response, int dataStatus) {
            if(response != null && response.data != null){
                if(response.data.citylist != null && response.data.carType != null && response.data.customerServicePhone != null) {
                    CarpoolSharedPreferences.setCacheMainConfigResponse(APIProxy.res().getBaseActivity(), response);
                }
            } else {
            }
        }
    };
    /**入口所需显示的数据，缓存在本地*/
    private MainInfoResponse mainInfoResponse;
    private IDataStatusChangedListener<MainInfoResponse> mainInfoResponseListener = new IDataStatusChangedListener<MainInfoResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData<MainInfoResponse> data, MainInfoResponse response, int dataStatus) {
            if(response != null && response.data != null&& response.errorNo == 0){
                if(CarpoolSharedPreferences.getCacheMainInfoResponse(APIProxy.res().getBaseActivity()) == null){
                    //第一次进入 等待网络请求再渲染 并存储
                    updateUI(response);
                    if(isSupportCarpool()){
                        mView.setVisibility(View.VISIBLE);
                    } else {
                        mView.setVisibility(View.GONE);
                        return;
                    }
                }
                if(TextUtils.isEmpty(response.data.price)){
                    mPriceTv.setVisibility(View.GONE);
                } else {
                    mPriceTv.setVisibility(View.VISIBLE);
                    mPriceTv.setText("(" + response.data.price + ")");
                }
                CarpoolSharedPreferences.setCacheMainInfoResponse(APIProxy.res().getBaseActivity(), response);
            } else {
                mView.setVisibility(View.GONE);
            }
        }
    };


    public EntranceInRoute(Context context, ViewGroup parent) {
        saveHomeAndCompanyGeo();
        LayoutInflater inflater = APIProxy.res().getInflater();
        mainConfigResponse = CarpoolSharedPreferences.getCacheMainConfigResponse(APIProxy.res().getBaseActivity());
        mView = (LinearLayout) inflater.inflate(R.layout.layout_carpool_entrance , parent , false);
        mView.setVisibility(View.GONE);
        initView();
        loadData();
        if(CarpoolSharedPreferences.getCacheMainInfoResponse(APIProxy.res().getBaseActivity()) != null){
            //非第一次进入 拿上一次的结果
            updateUI(CarpoolSharedPreferences.getCacheMainInfoResponse(APIProxy.res().getBaseActivity()));
            if(isSupportCarpool()){
                mView.setVisibility(View.VISIBLE);
            } else {
                mView.setVisibility(View.GONE);
                return;
            }
        }
        parent.addView(mView);
    }

    private void loadData() {
        MainConfigData mainConfigData = new MainConfigData(APIProxy.res().getBaseActivity());
        if(mainConfigResponse != null && mainConfigResponse.data != null){
            mainConfigData.setCache(mainConfigResponse.data.cache);
        }
        mainConfigData.setCityCode(UserInfoSetting.getCityId());
        mainConfigData.get(mMainConfigResponseListener);

        MainInfoData mainInfoData = new MainInfoData(APIProxy.res().getBaseActivity());
        mainInfoData.setStartPlaceInfo(mHomeInfoMoc);
        mainInfoData.setArrivePlaceInfo(mCompanyInfoMoc);
        mainInfoData.post(mainInfoResponseListener);
    }

    private void updateUI(MainInfoResponse mainInfoResponse) {
        if(mainInfoResponse == null){
            mView.setVisibility(View.GONE);
            return;
        }
        if(mainInfoResponse.data != null){
            mView.setVisibility(View.VISIBLE);
            if(TextUtils.isEmpty(mainInfoResponse.data.desc)){
                mDescTv.setVisibility(View.GONE);
            } else {
                mDescTv.setVisibility(View.VISIBLE);
                mDescTv.setText(mainInfoResponse.data.desc);
            }

            if(!TextUtils.isEmpty(mainInfoResponse.data.title)){
                mTitleTv.setText(mainInfoResponse.data.title);
            }else{
                mTitleTv.setText("上下班搭乘顺风车更划算");
            }
        } else {
            mView.setVisibility(View.GONE);
        }

    }


    private void initView() {

        mIconIm = (ImageView) mView.findViewById(R.id.Im_entrance_icon);
        mTitleTv = (TextView) mView.findViewById(R.id.tv_entrance_title);
        mPriceTv = (TextView) mView.findViewById(R.id.tv_entrance_price);
        mDescTv = (TextView) mView.findViewById(R.id.tv_entrance_desc);

        if(isFirstUseCarpool()){
            mIconIm.setImageDrawable(APIProxy.res().getResources().getDrawable(R.drawable.entrance_icon_first));
        } else {
            mIconIm.setImageDrawable(APIProxy.res().getResources().getDrawable(R.drawable.entrance_icon));
        }
        mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                APIProxy.navi().navigateTo(CarpoolHomePage.class, null);
//                CarpoolSharedPreferences.setIsFristUse(APIProxy.res().getBaseActivity(), false);
                UserInfoSetting.goToWebShell("http://cp01-rdqa-pool406.cp01.baidu.com:8088/main/webapp?page=orderList");
            }
        });
    }

    private boolean isFirstUseCarpool() {

        return CarpoolSharedPreferences.isFristUse(APIProxy.res().getBaseActivity());
    }

    public boolean isSupportCarpool() {
        boolean supportCarpool = false;
        if(mainConfigResponse == null){
            return true;
        }
        if(mainConfigResponse.data == null){
            return supportCarpool;
        }
        if(mainConfigResponse.data.citylist == null){
            MainConfigData mainConfigData = new MainConfigData(APIProxy.res().getBaseActivity());
            mainConfigData.setCityCode(UserInfoSetting.getCityId());
            mainConfigData.get(mMainConfigResponseListener);
            return supportCarpool;
        }

        ArrayList<MainConfigResponse.MainConfig.CityItem> citylist = new ArrayList<MainConfigResponse.MainConfig.CityItem>();
        citylist =  mainConfigResponse.data.citylist;
        if(citylist == null){
            return supportCarpool;
        }
        if(citylist.size() == 0){
            return supportCarpool;
        }
        supportCarpool = false;
        for(int i = 0; i < citylist.size(); i++){
            if(citylist.get(i) != null){
                int currentCityId = SafeUtils.safeString2int(UserInfoSetting.getCityId());
                int supportCityId = SafeUtils.safeString2int(citylist.get(i).cityCode);
                if(currentCityId == supportCityId){
                    return true;
                }
            }
        }

        return supportCarpool;
    }

    private CarpoolPosition mHomeInfoLL;
    private CarpoolPosition mCompanyInfoLL;
    private CarpoolPosition mHomeInfoMoc;
    private CarpoolPosition mCompanyInfoMoc;
    private void saveHomeAndCompanyGeo(){

        mHomeInfoMoc = new CarpoolPosition();
        mCompanyInfoMoc = new CarpoolPosition();
        mHomeInfoLL = new CarpoolPosition();
        mCompanyInfoLL = new CarpoolPosition();

        Preferences preferences = Preferences.build(APIProxy.sys().getApplicationContext());
        String companyAddr = preferences.getString(CarpoolEntity.SHORTCUT_COMPANY_ADDR, "");
        String companyGeo = preferences.getString(CarpoolEntity.SHORTCUT_COMPANY_GEO, "");
        String homeAddr = preferences.getString(CarpoolEntity.SHORTCUT_HOME_ADDR, "");
        String homeGeo = preferences.getString(CarpoolEntity.SHORTCUT_HOME_GEO, "");

        GeoPoint companyGeoPtLL = MapUtils.mc2ll(ComAPIManager.getComAPIManager().getCoordinateApi().getGeoPointFromString(companyGeo));
        GeoPoint homeGeoPtLL = MapUtils.mc2ll(ComAPIManager.getComAPIManager().getCoordinateApi().getGeoPointFromString(homeGeo));
        GeoPoint companyGeoPtMoc = ComAPIManager.getComAPIManager().getCoordinateApi().getGeoPointFromString(companyGeo);
        GeoPoint homeGeoPtMoc = ComAPIManager.getComAPIManager().getCoordinateApi().getGeoPointFromString(homeGeo);


        mHomeInfoLL.x = homeGeoPtLL.getLongitude();
        mHomeInfoLL.y = homeGeoPtLL.getLatitude();
        mHomeInfoLL.address = homeAddr;
        mCompanyInfoLL.x = companyGeoPtLL.getLongitude();
        mCompanyInfoLL.y = companyGeoPtLL.getLatitude();
        mCompanyInfoLL.address = companyAddr;

        mHomeInfoMoc.x = homeGeoPtMoc.getLongitude();
        mHomeInfoMoc.y = homeGeoPtMoc.getLatitude();
        mHomeInfoMoc.address = homeAddr;
        mCompanyInfoMoc.x = companyGeoPtMoc.getLongitude();
        mCompanyInfoMoc.y = companyGeoPtMoc.getLatitude();
        mCompanyInfoMoc.address = companyAddr;
        if(!"".equals(mHomeInfoMoc.address) && mHomeInfoMoc.x != 0.0 && mHomeInfoMoc.y != 0.0){
            CarpoolSharedPreferences.setHomeGeoAddrInfo(APIProxy.res().getBaseActivity(), mHomeInfoMoc);
        }
        if(!"".equals(mCompanyInfoMoc.address) && mCompanyInfoMoc.x != 0.0 && mCompanyInfoMoc.y != 0.0) {
            CarpoolSharedPreferences.setCompanyGeoAddrInfo(APIProxy.res().getBaseActivity(), mCompanyInfoMoc);
        }
    }
}
